/**
 *                            License
 * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS  
 * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). 
 * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.  
 * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR  
 * COPYRIGHT LAW IS PROHIBITED.
 * 
 * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND  
 * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE  
 * MAY BE CONSIDERED TO BE A CONTRACT,
 * THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED 
 * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
 * 
 */
package lineage.util;

import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据流.
 * 
 * @version 2014年3月8日下午5:44:01
 * @author jrwz
 */
public final class StreamUtil {
    private static final Logger LOG = LoggerFactory.getLogger(StreamUtil.class);

    /**
     * 关闭此流并释放与此流关联的所有系统资源.
     * 如果已经关闭该流,则调用此方法无效.
     * 
     * @param closeables
     *            - 可以关闭的数据源或目标
     */
    public static void close(final Closeable... closeables) {
        for (final Closeable c : closeables) {
            try {
                if (c != null) {
                    c.close();
                }
            } catch (final IOException e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
    }

    /**
     * 关闭套接字(服务端).
     * 
     * @param serverSocket
     *            - 服务端套接字
     */
    public static void close(final ServerSocket serverSocket) {
        try {
            if (!serverSocket.isClosed()) {
                serverSocket.close(); // 关闭此套接字。 在 accept() 中所有当前阻塞的线程都将会抛出 SocketException。如果此套接字有一个与之关联的通道，则关闭该通道。
            }
        } catch (final IOException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }

    /**
     * 关闭套接字(客户端).
     * 
     * @param socket
     *            - 客户端套接字
     */
    public static void close(final Socket socket) {
        try {
            if (!socket.isClosed()) {
                socket.shutdownInput(); // 此套接字的输入流置于“流的末尾”。发送到套接字的输入流端的任何数据都将被确认然后被悄悄丢弃。
                socket.shutdownOutput(); // 禁用此套接字的输出流。对于 TCP 套接字，任何以前写入的数据都将被发送，并且后跟 TCP 的正常连接终止序列。
                socket.close(); // 关闭此套接字也将会关闭该套接字的 InputStream 和 OutputStream。如果此套接字有一个与之关联的通道，则关闭该通道。
            }
        } catch (final IOException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
}
